package com.cskaoyan.service.impl;

import com.cskaoyan.exception.StockValidationException;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.cskaoyan.model.bo.CartBO;
import com.cskaoyan.model.bo.CheckOutOrderBO;
import com.cskaoyan.model.vo.*;
import com.cskaoyan.service.CartService;
import com.cskaoyan.service.WxCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: mall38
 * @description: 购物车模块
 * @author: Lexis
 * @create: 2022-05-08 22:26
 **/
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    Groupon_rulesMapper groupon_rulesMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    SystemMapper systemMapper;

    @Autowired
    WxCouponService wxCouponService;

    @Override
    /**
     * @author: lixiaosheng
     * @description: 查询购物车信息
     * @date: 2022/5/9 13:46
     */
    public CartVO queryCartInfo(String username) {
        Integer userId = userMapper.selectUserIdByUsername(username);
        CartExample cartExample = new CartExample();
        cartExample.setOrderByClause("add_time");
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<Cart> cartList = cartMapper.selectByExample(cartExample);
        CartTotalVO cartTotal = new CartTotalVO();
        CartTotalVO total = cartMapper.selectAmountAndCount(userId);
        CartTotalVO checked = cartMapper.selectAmountAndCountByChecked(1, userId);
        if (checked != null) {
            cartTotal.setCheckedGoodsCount(checked.getCheckedGoodsCount());
            cartTotal.setCheckedGoodsAmount(checked.getCheckedGoodsAmount());
        }
        if (total != null) {
            cartTotal.setGoodsCount(total.getGoodsCount());
            cartTotal.setGoodsAmount(total.getGoodsAmount());
        }
        return new CartVO(cartList, cartTotal);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 选取商品
     * @date: 2022/5/9 16:39
     */
    public void updateCheckedByGoodsId(CartBO cartBO, String username) {
        Integer userId = userMapper.selectUserIdByUsername(username);
        Cart cart = new Cart();
        cart.setChecked(cartBO.getIsChecked() == 1);

        for (Integer productId : cartBO.getProductIds()) {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andProductIdEqualTo(productId);
            criteria.andUserIdEqualTo(userId);
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 更新购物车商品的数量
     * @date: 2022/5/9 14:02
     */
    public void updateOrderById(UpdateOrderVO updateOrderVO) {
        Cart cart = new Cart();
        cart.setNumber(updateOrderVO.getNumber());
        cart.setId(updateOrderVO.getId());
        cartMapper.updateByPrimaryKeySelective(cart);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 根据规格id逻辑删除一条购物车订单
     * @date: 2022/5/9 12:31
     */
    public CartVO deleteOrderByProductId(List<Integer> productIds, String username) {
        Integer userId = userMapper.selectUserIdByUsername(username);
        for (Integer productId : productIds) {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andDeletedEqualTo(false);
            criteria.andProductIdEqualTo(productId);
            Cart cart = new Cart();
            cart.setDeleted(true);
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
        return queryCartInfo(username);
    }

    @Override
    /**
     * @author: lixiaosheng
     * @description: 查询订单信息
     * @date: 2022/5/9 13:23
     */
    public CheckOutOrderVO checkOutOrder(CheckOutOrderBO check, String username) {
        Integer userId = userMapper.selectUserIdByUsername(username);

        DataVO<WxCouponVO> data = wxCouponService.selectAvailableCouponList(userId, check.getCartId());

        // 获取当前可用的优惠券
        long availableCounponLength = 0L;

        double maxCouponPrice = 0.0;
        Integer maxCouponId = 0;

        Double couponPrice = 0.0;
        Integer couponId = check.getCouponId();

        boolean flag = false;
        for (WxCouponVO couponVO : data.getList()) {
            if (couponVO.getAvailable()) {
                availableCounponLength += 1;

                if (Objects.equals(couponVO.getCid(), couponId)) {
                    flag = true;
                    couponPrice = couponVO.getDiscount();
                }

                if (couponVO.getDiscount() > maxCouponPrice) {
                    maxCouponPrice = couponVO.getDiscount();
                    maxCouponId = couponVO.getId();
                }
            }
        }
        Integer userCouponId = check.getUserCouponId();
        if (check.getCouponId() == -1) {
            flag = true;
        }
        if (!flag) {
            couponPrice = maxCouponPrice;
            couponId = maxCouponId;
            userCouponId = couponUserMapper.selectIdByCouponId(couponId);
        }


        List<Cart> checkedGoodsList = new ArrayList<>();
        if (check.getCartId() != 0) {
            Cart cart = cartMapper.selectByPrimaryKey(check.getCartId());
            checkedGoodsList.add(cart);
        } else {
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);
            List<Cart> cartList = cartMapper.selectByExample(cartExample);
            checkedGoodsList.addAll(cartList);
        }

        // 获取商品总价
        double goodsTotalPrice = 0.0;
        for (Cart cart : checkedGoodsList) {
            goodsTotalPrice += cart.getPrice() * cart.getNumber();
        }

        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);

        boolean addressFlag = false;
        Integer addressId = check.getAddressId();
        List<Address> addressList = addressMapper.selectByExample(addressExample);
        Integer defautId = 0;
        for (Address address : addressList) {
            if (Objects.equals(address.getId(), check.getAddressId())) {
                addressFlag = true;
            }
            if (address.getIsDefault()) {
                defautId = address.getId();
            }
        }
        Address checkedAddress;
        if (addressFlag) {
            checkedAddress = addressMapper.selectByPrimaryKey(check.getAddressId());
        } else {
            addressId = defautId;
            checkedAddress = addressMapper.selectByPrimaryKey(defautId);
        }
        // 获取地址信息


        // 获取运费
        double freightPrice = 0.0;
        double freight_min = systemMapper.selectValueByKeyName("market_express_freight_min");
        if (goodsTotalPrice < freight_min) {
            freightPrice = systemMapper.selectValueByKeyName("market_express_freight_value");
        }
        // 获取团购优惠
        Double grouponPrice = groupon_rulesMapper.selectDiscountById(check.getGrouponRulesId());

        // 计算实际价格
        double actualPrice = goodsTotalPrice + freightPrice;

        if (couponPrice != null) {
            actualPrice -= couponPrice;
        } else {
            couponPrice = 0.0;
        }
        if (grouponPrice != null) {
            actualPrice -= grouponPrice;
        } else {
            grouponPrice = 0.0;
        }

        return new CheckOutOrderVO(actualPrice, addressId, Math.toIntExact(availableCounponLength), check.getCartId()
                , checkedAddress, checkedGoodsList, couponId, couponPrice, freightPrice, goodsTotalPrice, grouponPrice, check.getGrouponRulesId(), actualPrice, userCouponId);
    }

    @Override
    public Integer queryCartGoodsCountByUsername(String username) {
        Integer userId = userMapper.selectUserIdByUsername(username);
        return cartMapper.selectGoodsCountByUserId(userId);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 再商城主页加入商品到购物车，判断库存，更改库存
     * @date: 2022/5/9 16:59
     */
    public Integer add(String username, int goodsId, int number, int productId) throws StockValidationException {
        Integer cartId;
        Integer userId = userMapper.selectUserIdByUsername(username);
        int stockNum = goodsProductMapper.selectStockNumById(productId);
        if (stockNum < number) {
            throw new StockValidationException();
        } else {
            GoodsProduct goodsProduct = new GoodsProduct();
            goodsProduct.setNumber(stockNum - number);
            GoodsProductExample goodsProductExample = new GoodsProductExample();
            GoodsProductExample.Criteria criteria = goodsProductExample.createCriteria();
            criteria.andIdEqualTo(productId);
            goodsProductMapper.updateByExampleSelective(goodsProduct, goodsProductExample);
        }

        // 判断购物车里是否已有该商品
        Integer num = cartMapper.selectNumByGoodsIdAndProductIdAndUserId(userId, goodsId, productId);
        if (num != null) {
            cartId = cartMapper.selectCartIdByGoodsIdAndProductIdAndUserId(userId, goodsId, productId);
            Cart cart = new Cart();
            cart.setNumber((short) (num + number));
            cart.setUpdateTime(new Date());
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);
            criteria.andGoodsIdEqualTo(goodsId);
            cartMapper.updateByExampleSelective(cart, cartExample);
        } else {
            Cart cart = new Cart();
            cart.setAddTime(new Date());
            cart.setUpdateTime(new Date());
            cart.setNumber((short) number);
            cart.setGoodsId(goodsId);
            Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
            cart.setGoodsName(goods.getName());
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setPicUrl(goods.getPicUrl());
            GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
            cart.setPrice(goodsProduct.getPrice());
            cart.setUserId(userId);
            cart.setSpecifications(goodsProduct.getSpecifications());
            cart.setProductId(productId);
            cartMapper.insertSelective(cart);
            cartId = cart.getId();
        }
        return cartId;
    }
}
